package controllers

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"my-gin-tiktok/app/daos"
	"my-gin-tiktok/app/services"
	"my-gin-tiktok/common/message"
	"my-gin-tiktok/common/response"
)

// Register 注册
func Register(ctx *gin.Context) {
	var form daos.Register
	if err := ctx.ShouldBind(&form); err != nil {
		response.ValidateFail(ctx, message.GetErrorMsg(form, err))
		return
	}

	_, err := services.UserService.GetUserByName(ctx, form.Username)
	if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) {
		response.BusinessFail(ctx, err.Error())
		return
	}

	user, err := services.UserService.CreateUser(ctx, form.Username, form.Password)
	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}

	tokenData, err, _ := services.JwtService.CreateToken(services.AppGuardName, user)
	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}
	response.Success(ctx, tokenData)

}

// Login 登陆
func Login(ctx *gin.Context) {
	var form daos.Login
	if err := ctx.ShouldBind(&form); err != nil {
		response.ValidateFail(ctx, message.GetErrorMsg(form, err))
		return
	}

	user, err := services.UserService.GetUserByName(ctx, form.Username)
	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}

	if user.Password != form.Password {
		response.BusinessFail(ctx, "密码错误")
		return
	}

	tokenData, err, _ := services.JwtService.CreateToken(services.AppGuardName, user)
	if err != nil {
		response.BusinessFail(ctx, err.Error())
		return
	}
	response.Success(ctx, tokenData)
}
